#include "TrainposView.h"
#include <QMouseEvent>
#include <QApplication>
#include <QHBoxLayout>
#include <QBitmap>

#include "common.h"
#include "huaqimovie.h"

int TrainposView::m_id = qRegisterMetaType<TrainposView*>();
int ObjectShowFullscreenFlag = 0;

TrainposView::TrainposView(QWidget *parent)
    :ViewObject(parent)
    ,m_label(NULL)
    ,m_movie(NULL)
    ,hq_movie(NULL)
    ,m_TrainposViewParam(NULL)
{
    setWindowFlags(Qt::FramelessWindowHint);
    setAttribute(Qt::WA_DeleteOnClose);
    m_label = new QLabel(this);
    m_label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_label->setAlignment(Qt::AlignCenter);
    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(m_label, 0, Qt::AlignCenter);
    layout->setContentsMargins(0, 0, 0, 0);
    setContentsMargins(0, 0, 0, 0);
    setLayout(layout);
#ifdef __linux__
    setFocusPolicy(Qt::NoFocus);
#else
    setFocusPolicy(Qt::StrongFocus);
#endif

    if (m_objectParam == NULL)
        m_objectParam = new ParamObject;

    if (m_TrainposViewParam == NULL)
        m_TrainposViewParam = new TrainposViewParam;
}

TrainposView::~TrainposView()
{
    DestoryObject();
}

void TrainposView::ShowObject(QWidget* parent, QString filename, QString prefix, ProtocolData* ptr_data)
{

    //门状态(或者其他控件状态)是全屏的时候这个是不能显示的
    Q_UNUSED(filename);
    if (!m_TrainposViewParam || !m_objectParam || ObjectShowFullscreenFlag) return;

    setParent(parent);
    m_label->clear();

    QString url = "car_left_1";

    if (ptr_data)
    {
        int car_num = ptr_data->car_number;
        bool is_mirror = ptr_data->file_path.contains("mirror");
        int run_dir = RUN_INVALID;
        int start_id = ptr_data->start_id;
        int stop_id = ptr_data->stop_id;
        if (start_id <= stop_id)
            run_dir = RUN_UP;
        else
            run_dir = RUN_DOWN;

        if (run_dir == RUN_INVALID)
            return;

        if (ptr_data->key_position == 1)
        {
            if (is_mirror)
                url = QString("car_left_%1").arg(car_num);
            else
                url = QString("car_right_%1").arg(car_num);
        }

        if (ptr_data->key_position == 2)
        {
            if (is_mirror)
                url = QString("car_right_%1").arg(car_num);
            else
                url = QString("car_left_%1").arg(car_num);
        }
    }

    mPrefix = prefix;

#ifdef __WIN32__
    if (mPrefix == "")
        mPrefix = QString("%1/res/img/").arg(myapp::mDynamicMapParam->m_project_path);
#endif

    bool change = false;
    int change_x = 0;
    int change_y = 0;
    int change_w = 0;
    int change_h = 0;

    if (ptr_data)
    {
        for (auto it = ptr_data->items_change.begin(); it != ptr_data->items_change.end(); it++)
        {
            if (!it.key().compare(m_objectParam->GetName()))
            {
                change = true;

                if (it.value().x != DEFAULTVAL)
                {
                    change_x = it.value().x;
                }
                else
                {
                    change_x = m_objectParam->GetX();
                }
                if (it.value().y != DEFAULTVAL)
                {
                    change_y = it.value().y;
                }
                else
                {
                    change_y = m_objectParam->GetY();
                }
                if (it.value().w != DEFAULTVAL)
                {
                    change_w = it.value().w;
                }
                else
                {
                    change_w = m_objectParam->GetWidth();
                }
                if (it.value().h != DEFAULTVAL)
                {
                    change_h = it.value().h;
                }
                else
                {
                    change_h = m_objectParam->GetHeight();
                }
                if (it.value().content != "")
                {
                    url = it.value().content;
                    //此处不是直接赋值，是因为这里url计算好了，差异只需要加一下前缀，避免mvc也处理一下图片名称的拼接
                    //url.push_front(it.value().content);
                }
            }
        }
    }

    url = myapp::find_file(mPrefix, url);

    if (ptr_data)
    {
        add_suffix(url, ptr_data->suffix);
    }

    if (url != "")
    {
        LOG_QDEBUG << "TrainposView-------" << url;

        url.push_front(mPrefix);

        if ("hqv" == url.right(3))
        {
            if (myapp::isDirExist(url))
            {
                if (hq_movie == NULL)
                {
                    hq_movie = new HuaqiMovie(this);
                    if (NULL == hq_movie)
                        return;
                }
                else
                {
                    hq_movie->stop();
                }

                hq_movie->setFileName(url);
                QStringList list = hq_movie->getImageList();
                if (list.count() < 0)
                    return;
                m_label->setFixedSize(QSize(m_objectParam->GetWidth(), m_objectParam->GetHeight()));
                hq_movie->setLabel(m_label);
                hq_movie->start();
 #ifndef __linux__
                emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
 #endif
            }
        }
        else
        {
            // 解决设置gif图片之前设置过hqv资源，会继续显示hqv资源
            if (NULL != hq_movie)
            {
                hq_movie->stop();
                hq_movie->setLabel(NULL);
            }

            if ("gif" == url.right(3))
            {
                if (NULL == m_movie)
                {
                    m_movie = new QMovie(url, QByteArray(), this);
                    if (NULL == m_movie)
                        return;
                }
                else
                {
                    m_movie->stop();
                }
                m_movie->setFileName(url);
                m_movie->start();
                m_movie->setScaledSize(QSize(m_objectParam->GetWidth(), m_objectParam->GetHeight()));
                m_label->setMovie(m_movie);
 #ifndef __linux__
                emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
 #endif
            }
            else
            {
                QPixmap pixmap(url);
                m_label->setPixmap(pixmap);
                m_label->setScaledContents(true);

 #ifndef __linux__
                emit sgl_viewobject_update_to_editwidget(m_objectParam->GetRandom());
 #endif
            }
        }
    }
    else
    {
        m_label->setText(m_objectParam->GetObjectName());
    }

    if (change)
    {
        location(change_x, change_y, change_w, change_h);
    }
    else
    {
        location(m_objectParam->GetX(), m_objectParam->GetY(),
                    m_objectParam->GetWidth(), m_objectParam->GetHeight());
    }

    m_label->setFixedSize(size());
    show();
}

void TrainposView::HideObject()
{
    setParent(NULL);
    if (NULL != m_movie)
    {
        m_movie->stop();
    }
    hide();
}

void TrainposView::DestoryObject()
{
    HideObject();
    if (m_objectParam != NULL)
    {
        delete m_objectParam;
        m_objectParam = NULL;
    }

    if (m_TrainposViewParam != NULL)
    {
        delete m_TrainposViewParam;
        m_TrainposViewParam = NULL;
    }

    close();
}

void TrainposView::GetAttribute(std::string& attribute)
{   
    std::string jsonStr;
    Json::Value base;
    Json::StreamWriterBuilder writerBuilder;
    std::ostringstream os;

    base["zindex"] = QString::number(m_objectParam->GetIndex()).toStdString();
    base["stid"] = QString::number(m_objectParam->GetStId()).toStdString();
    base["x"] = QString::number(m_objectParam->GetX()).toStdString();
    base["y"] = QString::number(m_objectParam->GetY()).toStdString();
    base["w"] = QString::number(m_objectParam->GetWidth()).toStdString();
    base["h"] = QString::number(m_objectParam->GetHeight()).toStdString();
    base["name"] = m_objectParam->GetName().toStdString();

    std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
    jsonWriter->write(base, &os);
    jsonStr = os.str();

    attribute = jsonStr;
}

void TrainposView::SetAttribute(std::string jsonStr)
{
    bool res;
    JSONCPP_STRING errs;
    Json::Value root;
    Json::CharReaderBuilder readerBuilder;
    std::unique_ptr<Json::CharReader> const jsonReader(readerBuilder.newCharReader());
    res = jsonReader->parse(jsonStr.c_str(), jsonStr.c_str()+jsonStr.length(), &root, &errs);

    if (!res || !errs.empty())
        LOG_QDEBUG<<__FUNCTION__<<"json parse faild"<<QString::fromStdString(errs);

    if (CheckJsonValueType(root, "zindex", Json::stringValue))
        m_objectParam->SetIndex(QString::fromStdString(root["zindex"].asString()).toInt());

    if (CheckJsonValueType(root, "stid", Json::stringValue))
        m_objectParam->SetStId(QString::fromStdString(root["stid"].asString()).toInt());

    if (CheckJsonValueType(root, "x", Json::stringValue))
        m_objectParam->SetX(QString::fromStdString(root["x"].asString()).toInt());

    if (CheckJsonValueType(root, "y", Json::stringValue))
        m_objectParam->SetY(QString::fromStdString(root["y"].asString()).toInt());

    if (CheckJsonValueType(root, "w", Json::stringValue))
         m_objectParam->SetWidth(QString::fromStdString(root["w"].asString()).toInt());

    if (CheckJsonValueType(root, "h", Json::stringValue))
         m_objectParam->SetHeight(QString::fromStdString(root["h"].asString()).toInt());

    if (CheckJsonValueType(root, "name", Json::stringValue))
         m_objectParam->SetName(QString::fromStdString(root["name"].asString()));
}


void TrainposView::ParseXML(QDomElement* xmlDomEle)
{
    if (m_TrainposViewParam == NULL)
        m_TrainposViewParam = new TrainposViewParam;

    m_objectParam->SetIndex((xmlDomEle->attribute("zindex", "0")).toInt());
    m_objectParam->SetStId((xmlDomEle->attribute("stid", "0")).toInt());
    m_objectParam->SetX((xmlDomEle->attribute("x", "0")).toInt());
    m_objectParam->SetY((xmlDomEle->attribute("y", "0")).toInt());
    m_objectParam->SetWidth((xmlDomEle->attribute("w", "0")).toInt());
    m_objectParam->SetHeight((xmlDomEle->attribute("h", "0")).toInt());
    m_objectParam->SetName(xmlDomEle->attribute("name", ""));
}

void TrainposView::PacketXML(QDomElement* dom)
{
    QDomDocument document;
    *dom = document.createElement("item");
    dom->setAttribute("type", m_objectParam->GetObjectName());
    dom->setAttribute("zindex", QString::number(m_objectParam->GetIndex()));
    dom->setAttribute("stid", QString::number(m_objectParam->GetStId()));
    dom->setAttribute("x", QString::number(m_objectParam->GetX()));
    dom->setAttribute("y", QString::number(m_objectParam->GetY()));
    dom->setAttribute("w", QString::number(m_objectParam->GetWidth()));
    dom->setAttribute("h", QString::number(m_objectParam->GetHeight()));
    dom->setAttribute("name", m_objectParam->GetName());
}
